package com.alexsun.equation

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*

class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val spinner: Spinner = findViewById(R.id.spinner)
        ArrayAdapter.createFromResource(
            this,
            R.array.operator_array,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            spinner.adapter = adapter
        }

        spinner.onItemSelectedListener = this
    }

    override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id: Long) {
        val resEdit: EditText = findViewById(R.id.resNum)
        try {
            val num1 = findViewById<EditText>(R.id.editNum1).text.toString().toDouble()
            val num2 = findViewById<EditText>(R.id.editNum2).text.toString().toDouble()
            val res = when (pos) {
                0 -> num1 + num2
                1 -> num1 - num2
                2 -> num1 * num2
                3 -> num1 / num2
                else -> 0
            }
            resEdit.setText(res.toString().removeSuffix(".0"))
        } catch (e: java.lang.NumberFormatException) {
            Toast.makeText(this, "输入不合法", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onNothingSelected(parent: AdapterView<*>) {}
}